<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      :show-close="true"
      :append-to-body="true"
      class="add-field-dialog small-common-dialog-size"
      width="240px"
      @closed="handleClose"
    >
      <Title :title="title" font-size="16px" style="margin-bottom:20px;"/>
      <el-form ref="editFieldForm" :model="paramsObj" class="el-form-box-left" label-width="80px">
        <el-form-item label="分类名称" prop="name" class="client-type" style="margin-bottom:0px;">
          <el-input v-model="paramsObj.name" style="width:240px;" maxlength="8" size="small" placeholder="请输入分类名称"/>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" style="margin-top:30px;">
        <el-button class="cancel" size="small" @click="dialogVisible = false">取消</el-button>
        <el-button class="ok" size="small" type="primary" @click="handelOk">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Title from '@/components/Title';
import ElMessage from '@/utils/message';
import { addFieldType, editFieldType } from '@/api/fieldManage';

export default {
  components: { Title },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      isEdit: false,
      title: '新增分类',
      paramsObj: {
        name: ''
      }
    };
  },
  methods: {
    openDialog(data) {
      if (data) {
        this.isEdit = true;
        this.paramsObj = data;
        this.title = '编辑分类';
      } else {
        this.title = '新增分类';
        this.isEdit = false;
      }
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
      this.paramsObj = {};
    },
    handelOk() {
      if (!this.paramsObj.name || this.paramsObj.name === '') {
        ElMessage.error('请输入分类名称');
        return;
      }
      if (this.isEdit) {
        this.edit(this.paramsObj);
      } else {
        this.add(this.paramsObj);
      }
    },
    add(params) {
      addFieldType(params).then(res => {
        if (res.code === 200) {
          ElMessage.success('新增成功');
          this.handleClose();
          this.$emit('callback');
        } else {
          ElMessage.error(res.message);
        }
      });
    },
    edit(params) {
      editFieldType(params).then(res => {
        if (res.code === 200) {
          ElMessage.success('编辑成功');
          this.handleClose();
          this.$emit('callback');
        } else {
          ElMessage.error(res.message);
        }
      });
    }
  }
};
</script>

<style lang='scss' scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  .ok {
    width: 120px;
    font-size: 14px;
  }
  .cancel {
    width: 80px;
    font-size: 14px;
    color: #406EFF;
    background:rgba(239,243,251,1);
    border: none;
  }
}
</style>
